package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"time"
	"zg4/zk1/api/consts"
	"zg4/zk1/api/pkg"
	__ "zg4/zk1/api/proto"
	"zg4/zk1/api/request"
)

func UserLogin(c *gin.Context) {

	var req request.UserLoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("localhost:8899", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	xx := __.NewVideoClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	login, err := xx.UserLogin(ctx, &__.UserLoginRequest{
		Account:  req.Account,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	token, _ := pkg.NewJWT(consts.JWT_APP_KEY).CreateToken(pkg.CustomClaims{ID: uint(login.UserId)})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户登录成功",
		"data": token,
	})
	return
}
